﻿using System;
using System.Text;
using Viyi.Util.Codec;
using Xunit;

namespace Viyi.Util.Test.Codec
{
    public class TestBase64
    {
        // 对于正常的情况不需要测试，因为是直接调用的 Convert.ToBase64String 和 Convert.FromBase64String

        [Fact]
        public void Base64EncodeNull()
        {
            Assert.Null(((byte[]) null).Base64Encode());
            Assert.Null(((byte[]) null).Base64Encode(0, 64));
            Assert.Null(((byte[]) null).Base64Encode(true));
            Assert.Null(((string) null).Base64Encode());
            Assert.Null(((string) null).Base64Encode(Encoding.UTF8));
            Assert.Null(((string) null).Base64Encode(Encoding.UTF8, true));
            Assert.Null(((string) null).Base64Encode("utf-8"));
            Assert.Null(((string) null).Base64Encode("utf-8", true));
        }

        [Fact]
        public void Base64EncodeEmpty()
        {
            Assert.Equal(string.Empty, new byte[0].Base64Encode());
            Assert.Equal(string.Empty, new byte[0].Base64Encode(0, 0));
            Assert.Equal(string.Empty, new byte[0].Base64Encode(true));
            Assert.Equal(string.Empty, string.Empty.Base64Encode());
            Assert.Equal(string.Empty, string.Empty.Base64Encode(Encoding.UTF8));
            Assert.Equal(string.Empty, string.Empty.Base64Encode(Encoding.UTF8, true));
            Assert.Equal(string.Empty, string.Empty.Base64Encode("utf-8"));
            Assert.Equal(string.Empty, string.Empty.Base64Encode("utf-8", true));

            Assert.Throws<ArgumentOutOfRangeException>(() =>
            {
                Assert.Equal(string.Empty, new byte[0].Base64Encode(0, 1));
            });
        }

        [Fact]
        public void Base64EncodeWithUnknownEncoding()
        {
            Assert.Throws<ArgumentException>(() =>
            {
                "abcdefg".Base64Encode("blabla-encoding");
            });

            Assert.Throws<ArgumentException>(() =>
            {
                "abcdefgh".Base64Decode("blabla-encoding");
            });
        }

        [Fact(DisplayName = "Base64格式不正确抛异常")]
        public void Base64DecodeError()
        {
            Assert.Throws<FormatException>(() =>
            {
                "abcde".Base64Decode();
            });

            Assert.Throws<FormatException>(() =>
            {
                "!@#$%^&*".Base64Decode();
            });
        }
    }
}
